package com.wavehi.config;

import com.alibaba.druid.pool.DataSourceClosedException;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.codegen.bean.Property;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author WaveHi
 * @Date 24/10/2021 下午 1:53
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
@Configuration @ComponentScan(basePackages = {"com.wavehi"}) @EnableTransactionManagement
public class SpringConfig {
    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource getDruidDataSource() throws IOException {
        InputStream in = SpringConfig.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(in);//获取配置文件属性集
        DruidDataSource druidDataSource = new DruidDataSource();//设置数据源
        druidDataSource.setDriverClassName(properties.getProperty("mysql.driverClassName"));
        druidDataSource.setUrl(properties.getProperty("mysql.url"));
        druidDataSource.setUsername(properties.getProperty("mysql.username"));
        druidDataSource.setPassword(properties.getProperty("mysql.password"));
        return druidDataSource;
    }
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}
